package com.ilock.bean;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ilock.config.HibernateSessionFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * Ilockloc entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.ilock.bean.Ilockloc
 * @author MyEclipse Persistence Tools
 */
public class IlocklocDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(IlocklocDAO.class);
	// property constants
	public static final String ILOCK_LOC_LNG = "ilockLocLng";
	public static final String ILOCK_LOC_LAT = "ilockLocLat";

	protected void initDao() {
		// do nothing
	}

	public void save(Ilockloc transientInstance) {
		log.debug("saving Ilockloc instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public List getLocationListbyTime(int lockID,Timestamp timestamp){
		String queryString = "from Ilockloc as model where model.ilockInfoNumber= ?"+
				 " and model.ilockLocTime> ?";
			return getHibernateTemplate().find(queryString,lockID,timestamp);
	}
	/**
	 * get lock's latest location by id
	 * @param lockId
	 * @return
	 */
	/*public Ilockloc getLatestLocation(int lockId){
		Ilockloc ilockloc = null;
		String queryString = "from Ilockloc as model where model.ILockInfoNumber="+lockId+
							 " order by IlocklocTime desc";
		List locklocList = getHibernateTemplate().find(queryString);
		if(!locklocList.isEmpty()){
			ilockloc = (Ilockloc) locklocList.get(0);
		}
		return ilockloc;
	}*/
	public void delete(Ilockloc persistentInstance) {
		log.debug("deleting Ilockloc instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public List<Ilockloc> findNearbyLock(int lockId,double distance){
		
		log.debug("find nearby user by location,id: " +lockId );
		try{
			String queryString ="from Ilockloc where ((ilockLocLng*ilockLocLng+ilockLocLat*ilockLocLat)<?) group by ilockInfoNumber";
			return getHibernateTemplate().find(queryString, distance);
		}catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List testHql(int lockId,double distance){
		String queryString ="from ilockloc where ((ilockLocLng*ilockLocLng+ilockLocLat*ilockLocLat)<?) group by ilockInfoNumber";
		HibernateSessionFactory hs = new HibernateSessionFactory(); 
		Session ss = hs.getSession();
		Query query =ss.createQuery(queryString);
		query.setMaxResults(20);
		return query.list();
	}
	public Ilockloc findById(java.lang.Integer id) {
		log.debug("getting Ilockloc instance with id: " + id);
		try {
			Ilockloc instance = (Ilockloc) getHibernateTemplate().get(
					"com.ilock.bean.Ilockloc", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Ilockloc instance) {
		log.debug("finding Ilockloc instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Ilockloc instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Ilockloc as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByIlockLocLng(Object ilockLocLng) {
		return findByProperty(ILOCK_LOC_LNG, ilockLocLng);
	}

	public List findByIlockLocLat(Object ilockLocLat) {
		return findByProperty(ILOCK_LOC_LAT, ilockLocLat);
	}

	public Ilockloc getLockLatestLocation(int lockID){
		log.debug("getting Ilockloc latest location by lockid:"+lockID);
		Ilockloc tempilockloc = null;	
		try {
			String queryString = "from Ilockloc as b where b.ilockLocTime in ("
					+ "select max(a.ilockLocTime) from Ilockloc as a where a.ilockInfoNumber="
					+ lockID+") and b.ilockInfoNumber="+lockID;
			List templist = getHibernateTemplate().find(queryString);
			if(!templist.isEmpty()){
				tempilockloc = (Ilockloc) templist.get(0);
			}else{
				System.out.println("getting latest location error with empty list by id:"+lockID);
			}
		} catch (RuntimeException re) {
			log.error("getting latest location error", re);
			throw re;
		}
		return tempilockloc;
		
	}
	
	public List getNearLockList(int lockID,double lat,double lng,double scope){
		log.debug("getting lock's near user list with lockID:"+lockID);
		List templist = null;
		try {
			String queryString = "from Ilockloc as a where a.ilockLocTime in "
					+ "(select max(b.ilockLocTime)from Ilockloc as b group by b.ilockInfoNumber) and "
					+ "((a.ilockLocLng-"+lng+")*(a.ilockLocLng-"+lng+") +(a.ilockLocLat-"+lat+")*(a.ilockLocLat-"+lat+")<"+scope*scope+")"
					+" and a.ilockInfoNumber!="+lockID;
			templist = getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("getting near user list error", re);
			throw re;
		}
		return templist; 
	}
	
	public List getLoseConnLockList(){
		log.debug("get  lose connection lock list");
		try {
			String queryString = "select b.ilockInfoNumber from Ilockloc as b "
					+ "where b.ilockLocTime in(select max(a.ilockLocTime) from Ilockloc as a "
					+ "group by a.ilockInfoNumber) and (((CURRENT_TIMESTAMP()-b.ilockLocTime)>100 and (CURRENT_TIMESTAMP()-b.ilockLocTime)<150) or "
					+ "((CURRENT_TIMESTAMP()-b.ilockLocTime)>300 and (CURRENT_TIMESTAMP()-b.ilockLocTime)<350) or"
					+ "((CURRENT_TIMESTAMP()-b.ilockLocTime)>700 and (CURRENT_TIMESTAMP()-b.ilockLocTime)<750) or"
					+ "((CURRENT_TIMESTAMP()-b.ilockLocTime)>1500 and (CURRENT_TIMESTAMP()-b.ilockLocTime)<1550))";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findAll() {
		log.debug("finding all Ilockloc instances");
		try {
			String queryString = "from Ilockloc";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Ilockloc merge(Ilockloc detachedInstance) {
		log.debug("merging Ilockloc instance");
		try {
			Ilockloc result = (Ilockloc) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Ilockloc instance) {
		log.debug("attaching dirty Ilockloc instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Ilockloc instance) {
		log.debug("attaching clean Ilockloc instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static IlocklocDAO getFromApplicationContext(ApplicationContext ctx) {
		return (IlocklocDAO) ctx.getBean("IlocklocDAO");
	}
}